<script setup>
import SearchTable from "./component/SearchStatistics"
import moment from "moment";
import {getAlarmTimeRank, getAlarmCameraRank, getTodayAlarmTimeRank, getAmbulanceAlarmRank, getAlarmNumRank, getAlertable, getCurve, getDictDetail } from "./utils"

import * as echarts from 'echarts';
import { CirclePlus, VideoPlay } from '@element-plus/icons-vue'
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue"

const instance = getCurrentInstance()
const _this = instance.appContext.config.globalProperties //vue3获取当前this


// Today’s alarm analysis ==
const today = ref(null);
let todayFirst = true;
const todayLoading = ref(true);

// Comparative analysis of alarms  ==
const analysis = ref(null);
let analysisFirst = true;
const analysisLoading = ref(true);

// Camera Alarm Ranking ==
const dimensions = ref(null);
let dimensionsFirst = true;
const dimensionsLoading = ref(true);


// Alarm aggregation diagram  ==
let diagram = ref(null);
let diagramFirst = true;
let diagramLoading = ref(true);
let alarmTypeLists = ref([]);

// Alarm level proportion ==  
const proportion = ref(null);
let proportionFirst = true;
const proportionLoading = ref(true);

// Ranking of alarms for stationed units
const rankList = reactive([
  { label: 'None', value: 0, imgSrc: require('@/assets/image/ico_top1.png') },
  { label: 'None', value: 0, imgSrc: require('@/assets/image/ico_top2.png') },
  { label: 'None', value: 0, imgSrc: require('@/assets/image/ico_top3.png') },
  { label: 'None', value: 0, imgSrc: require('@/assets/image/ico_top4.png') },
  { label: 'None', value: 0, imgSrc: require('@/assets/image/ico_top5.png') },
])

const searchForm = reactive({
  date: [moment().subtract(1, 'months').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
  ambulanceId: '',
  alarmType: ''
})

function onSearch(){
  init();
}

async function init(){
  let time = new Date()
  let paramsTodayCurve = {
    startTime: moment(time).format("YYYY-MM-DD") + ' 00:00:00',
    endTime: moment(time).format("YYYY-MM-DD") + ' 23:59:59',
  }
  let params = {
    // ambulanceId: searchForm.ambulanceId,
    startTime: searchForm.date && searchForm.date[0] + ' 00:00:00' || moment(time).format("YYYY-MM-DD") + ' 00:00:00',
    endTime: searchForm.date && searchForm.date[1] + ' 23:59:59' || moment(time).format("YYYY-MM-DD") + ' 23:59:59',
  }
  // 前三个排行
  let getAlarmNumRanks = await getAlarmNumRank(instance, params);

  let getAlarmCameraRanks = await getAlarmCameraRank(instance, params);
  let getAlarmTimeRanks = await getAlarmTimeRank(instance, params);
  let getTodayAlarmTimeRanks = await getTodayAlarmTimeRank(instance, paramsTodayCurve);

  // let getAlarmUnitRanks = await getAlarmUnitRank(instance, params)
  // let getAmbulanceAlarmRanks = await getAmbulanceAlarmRank(instance, params)
  // let getAlertables = await getAlertable(instance, params)
  // let getCurves = await getCurve(instance, params)  // []  0:虚线  1：实线
  // let todayCurves = await getTodayCurve(instance, paramsTodayCurve)
  
  // Ranking of alarms for stationed units
  rankList.map((i, ind) => {
    let item = getAlarmNumRanks.data[ind];
    i.value = item && item.num || 0;
    i.label = item && item.name || 'None';
    return i;
  });
  let maxRank = rankList[0].value;
  rankList.value = rankList.map(i => {
    i['progress'] = ((i.value / maxRank) * 100).toFixed(2);
    return i;
  })

  // Alarm level proportion ==
  var proportionChartDom =  proportion.value;
  var proportionChart = echarts.init(proportionChartDom);
  let proportionOption = {
    legend: {
      bottom: '5%',
      left: 'center',
      textStyle: {
        color: '#ffffff'
      }
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['40%', '48%'],
        avoidLabelOverlap: false,
        top: 0,
        bottom: 50,
        itemStyle: {
          borderRadius: 99999,
          borderColor: 'transparent',
          borderWidth: 10
        },
        label: {
          show: false,
          position: 'center',
          // formatter(params){ 
          //   return `${params.data.value}  ${params.percent}%`
          // },
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 26,
            formatter(params){ 
              return `${params.percent}%`
            },
            fontWeight: 'bold'
          },
        },
        labelLine: {
          show: false
        },
        data: getAlarmNumRanks.data.map(i => {
          i['name'] = i.name;
          i['value'] = i.num;
          return i;
        })
      }
    ]
  };
  proportionChart.on('finished', _ => {
    if(proportionFirst){
      proportionFirst = false;
      proportionLoading.value = false; //关闭loading
    };
  });
  proportionChart.setOption(proportionOption);
  
  // Alarm aggregation diagram  ==
  var diagramChartDom =  diagram.value;
  var diagramChart = echarts.init(diagramChartDom);
  let ciyunData = getAlarmNumRanks.data.map(i => {
    i['name'] = i.name;
    i['value'] = i.num;
    return i;
  })
  //偏移量
  var offsetData = [
      [40, 35],
      [50, 65],
      [67, 75],
      [64, 25],
      [16, 25],
      [20, 70],
      [77, 45],
      [20, 50]
  ];
  const max = ciyunData.reduce(function (prev, next) {
      return Math.max(prev, next.value);
  }, 0);

  const sortData = ciyunData.sort((x, y) => y.value - x.value);
  
  const data = sortData.map((d, i) => {
      const scale = d.value / max;
      return {
          name: d.name,
          value: offsetData[i],
          symbol: 'circle',
          symbolSize: scale * 100,
          source: d.value,
          label: {
            color: "#ffffff",
            fontSize: 14
              // normal: {
                // textStyle: {
                // }
              // }
          }
      }
  });
  let diagramOption = {
      color: ['rgba(252, 90, 165, 0.9)'],
      grid: {
          top: 0,
          bottom: 0,
          left: 0,
          right: 0
      },
      tooltip: {
          show: true,
          formatter(params){ 
              return `${params.name}：${sortData[params.dataIndex].value}`
          }
      },
      xAxis: [{
          type: "value",
          show: false,
          nameLocation: "middle",
          min: 0,
          max: 100,
          nameGap: 0
      }],
      yAxis: [{
          show: false,
          nameLocation: "middle",
          min: 0,
          max: 100,
          nameGap: 0
      }],
      series: [{
          type: "scatter",
          label: {
            show: true,
            align: "center",
            verticalAlign: 'middle',
            formatter(params){ 
              let str = 
              '{a|' + 
              params.data.source + 
              '} \n' +
              '{b|' + 
              params.data.name +'}'
              return str
            },
            rich: {
              a: {
                fontSize: '16px',
                color: '#FFFFFF'
              },
              b: {
                fontSize: '12px',
                color: '#ffffff'
              }
            },
            color: "#fff",
            fontSize: "20"
            // textStyle: {
            // }
              // normal: {
              // }
          },
          data: data
      }]
  };
  diagramChart.on('finished', _ => {
    if(diagramFirst){
      diagramFirst = false;
      diagramLoading.value = false; //关闭loading
    };
  });
  diagramChart.setOption(diagramOption);

  // Camera Alarm Ranking ==
  var dimensionsChartDom =  dimensions.value;
  var dimensionsChart = echarts.init(dimensionsChartDom);
  let dimensionsOption = {
    xAxis: {
      type: 'category',
      data: getAlarmCameraRanks.data.map(i => i.name),
      axisLabel: {  
        interval: 0,
        rotate: 0,
        align: 'center',
        margin: 10
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      bottom: 40
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#5F6060',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        data: getAlarmCameraRanks.data.map(i => i.num),
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          borderRadius: [9999, 9999, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2CA5FE' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#3A4EFC' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#3A4EFC' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#2CA5FE' }
            ])
          }
        },
      }
    ]
  };
  dimensionsChart.on('finished', _ => {
    if(dimensionsFirst){
      dimensionsFirst = false;
      dimensionsLoading.value = false; //关闭loading
    };
  });
  dimensionsChart.setOption(dimensionsOption);

  // Comparative analysis of alarms   ==
  var analysisChartDom =  analysis.value;
  var analysisChart = echarts.init(analysisChartDom);
  let analysisOption = {
    tooltip: {
      trigger: 'axis',
      formatter(arr){ 
        let str = ''
        arr.forEach(i => {
          str += i.name + '<br>'+ i.marker + i.seriesName + '：' + i.value + '<br>'
        })
        return str
      },
    },
    legend: {
      show: true,
      data: ['The Day Before', 'Current'],
      bottom: 0,
      textStyle: {
        color: '#D3D5D6'
      }
    },
    xAxis: {
      type: 'category',
      data: getAlarmTimeRanks.data[1].map(i => i.time)
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#5F6060',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: 'The Day Before',
        data: getAlarmTimeRanks.data[0].map(i => {
          return {
            value: i.num,
            name: i.time,
            time: i.time,
          }
        }),
        type: 'line',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      {
        name: 'Current',
        data: getAlarmTimeRanks.data[1].map(i => {
          return {
            value: i.num,
            time: i.time,
            name: i.time
          }
        }),
        type: 'line',
        showSymbol: false,
        smooth: true,
      },
    ]
  };
  analysisChart.on('finished', _ => {
    if(analysisFirst){
      analysisFirst = false
      analysisLoading.value = false //关闭loading
    }
  })
  analysisChart.setOption(analysisOption);
  

  // Today’s alarm analysis == 
  var todayChartDom = today.value;
  var todayChart = echarts.init(todayChartDom);
  let todayOption = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      right: 60,
      bottom: 40
    },
    xAxis: {
      type: 'category',
      // boundaryGap: false,     moment().format('HH:MM')
      data: getTodayAlarmTimeRanks.data.map(i => i.time.substr(11) ),
      axisLabel: {  
        interval: 0,
        rotate: 0,
        align: 'center',
        margin: 10
      }
      // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: 'Today',
        data: getTodayAlarmTimeRanks.data.map(i => i.num ),
        // data: [620, 632, 601, 634, 1190, 1230, 1120],
        type: 'line',
        showSymbol: false,
        smooth: true,
        lineStyle: {
          color:  new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#2CFCFE' },
            { offset: 1, color: '#3A4EFC' }
          ])
        },
        areaStyle: {
          opacity: 0.2,
          color:  new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#2CFCFE' },
            { offset: 1, color: '#3A4EFC' }
          ])
        }
      },
    ]
  };
  todayChart.on('finished', _ => {
    if(todayFirst){
      todayFirst = false;
      todayLoading.value = false; //关闭loading
    }
  })
  todayChart.setOption(todayOption);

  
}

// 生命周期
onMounted(() => {
  init();
  // getSelect();
})

let getSelect = async () => {
  let list = await getDictDetail(instance, {name: 'alarm_algorithm'});
  list.data.unshift({
    label: "All",
    value: ''
  })
  algorithmSelect.value = list.data;
  instance.proxy.$http.get('archiveData.getCitySelect').then(res=>{
    selectCity.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      return i;
    });
  });
}
const algorithmSelect = ref([]);
const selectCity = ref([]);

let updataEchart = async () => {
  let time = new Date();  
  let params = {
    ambulanceId: searchForm.ambulanceId,
    alarmType: searchForm.alarmType,
    startTime: searchForm.date && searchForm.date[0] + ' 00:00:00' || moment(time).format("YYYY-MM-DD") + ' 00:00:00',
    endTime: searchForm.date && searchForm.date[1] + ' 23:59:59' || moment(time).format("YYYY-MM-DD") + ' 23:59:59',
  }
  let getCurves = await getCurve(instance, params)  // []  0:虚线  1：实线
  
  // Comparative analysis of alarms ==
  var analysisChartDom =  analysis.value;
  var analysisChart = echarts.init(analysisChartDom);
  analysisLoading.value = true // 打开loading
  let analysisOption = {
    tooltip: {
      trigger: 'axis',
      formatter(arr){ 
        let str = ''
        arr.forEach(i => {
          str += i.name + '<br>'+ i.marker + i.seriesName + '：' + i.value + '<br>'
        })
        return str
      },
    },
    legend: {
      show: true,
      data: ['The Day Before', 'Current'],
      bottom: 0,
      textStyle: {
        color: '#D3D5D6'
      }
    },
    xAxis: {
      type: 'category',
      data: getCurves.data[1].map(i => i.time)
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#5F6060',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: 'The Day Before',
        data: getCurves.data[0].map(i => {
          return {
            value: i.num,
            name: i.time,
            time: i.time,
          }
        }),
        type: 'line',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      {
        name: 'Current',
        data: getCurves.data[1].map(i => {
          return {
            value: i.num,
            time: i.time,
            name: i.time
          }
        }),
        type: 'line',
        showSymbol: false,
        smooth: true,
      },
    ]
  };
  analysisChart.on('finished', _ => {
    analysisLoading.value = false //关闭loading
  })
  analysisChart.setOption(analysisOption);
}


</script>
<template>
  <div class="alarm_index">
    <SearchTable class="search_box" :searchForm="searchForm" @onSearch="onSearch" />
    <div class="total_row marBottom20 h360">
      <div class="total_item">
        <!-- <div class="title_item row_drop">Ranking of alarms for stationed units</div> -->
        <div class="title_item row_drop">Algorithm Ranking</div>
        <div class="rank_list">
          <div class="rank_item" v-for="(item, index) in rankList" :key="index">
            <img :src="item.imgSrc" alt="">
            <div class="rank_content">
              <div class="rank_title">{{ item.label }}</div>
              <div class="rank_progress" :style="{width: item.progress + '%'}"></div>
            </div>
            <div class="rank_val">{{ item.value }}</div>
          </div>
        </div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Algorithm proportion</div>
        <div ref="proportion" v-loading="proportionLoading" class="echarts_box"></div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Alarm Aggregation Diagram</div>
        <div ref="diagram" v-loading="diagramLoading" class="echarts_box"></div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Camera Alarm Ranking</div>
        <div ref="dimensions" v-loading="dimensionsLoading" class="echarts_box"></div>
      </div>
    </div>
    <div class="total_row h484">
      <div class="total_item  form_search_echarts">
        <div class="alarms_title">
          <div class="title_item row_drop">Alarm Trend</div>
          <!-- <el-select
            v-model="searchForm.alarmType"
            placeholder="Please Select"
            @change="updataEchart"
            clearable
          >
            <el-option v-for="item in algorithmSelect" :key="item.label" :label="item.label" :value="item.value" />
          </el-select> -->
        </div>
        <div ref="analysis" v-loading="analysisLoading" class="echarts_box h420"></div>
      </div>
      <div class="total_item">
        <div class="title_item row_drop">Today’s Alarm Trend</div>
        <div ref="today" v-loading="todayLoading" class="echarts_box h420"></div>
      </div>
    </div>  
  </div>
</template>
<style scoped lang="less">
.alarm_index{
  color: #fff;
  // height: 100%;
  padding: 20px;
  // height: 100%;
  display: flex;
  flex-direction: column;
  .total_row{
    display: flex;
    justify-content: space-between;
    .total_item{
      flex: 1;
      height: 100%;
      padding: 20px;
      margin-right: 20px;
      box-shadow: 0px 6px 12px 1px rgba(26,84,193,0.1);
      border-radius: 8px;
      background-color: rgba(25, 31, 43, 0.7);
      .alarms_title{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
      }
      .echarts_box{
        width: 100%;
        height: calc(100% - 24px);
      }
      .Ven_pic{
        width: 296px;
        height: calc(100% - 24px);  // 296px
        position: relative;
        margin: 0 auto;
        .Ven_value{
          position: absolute;
          transform: translate(-50%, -50%);
          user-select: none;
        }
        .Ven_value_phone{
          left: 24%;
          top: 30%;
        }
        .Ven_value_phone_smoke{
          left: 50%; 
          top: 25%;
        }
        .Ven_value_smoke{
          right: 20%;
          top: 30%;
        }
        .Ven_value_phone_wheelchair{
          left: 34%;
          top: 53%;
        }
        .Ven_value_phone_smoke_wheelchair{
          left: 50%;
          top: 44%;
        }
        .Ven_value_smoke_wheelchair{
          right: 28%;
          top: 53%;
        }
        .Ven_value_wheelchair{
          left: 50%;
          bottom: 22%;
        }
        .Ven_pic_round{
          position: absolute;
          transform: translate(-50%, -50%);
          width: 160px;
          height: 160px;
          border-radius: 99999px;
        }
        
        .txt_Phone{
          color: #FB393C;
          background-color: transparent;
        }
        .txt_Smoke{
          color: #F8780B;
          background-color: transparent;
        }
        .txt_Wheelchair{
          color: #E0AA26;
          background-color: transparent;
        }
        .Ven_pic_phone{
          top: 108px;
          left: calc(50% - 40px);
          background-color: rgba(230, 11, 24, 0.2);
          span{
            position: absolute;
            left: -20px;
            top: 4px;
          }
        }
        .Ven_pic_smoke{
          top: 108px;
          left: calc(50% + 40px);
          background-color: rgba(248, 120, 11, 0.2);
          span{
            position: absolute;
            right: -22px;
            top: 4px;
          }
        }
        .Ven_pic_wheelchair{
          bottom: -40px;
          left: 50%;
          background-color: rgba(224, 170, 38, 0.2);
          span{
            position: absolute;
            left: 50%;
            bottom: -30px;
            transform: translate(-50%, -50%);
          }
        }
      }
      .rank_list{
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        height: calc(100% - 24px);
        .rank_item{
          display: flex;
          align-items: center;
          justify-content: space-between;
          img{
            width: 30px;
            height: 30px;
          }
          .rank_content{
            flex: 1;
            margin: 0 10px;
            .rank_title{
              font-size: 14px;
            }
            .rank_progress{
              height: 6px;
              margin: 4px 0;
              border-radius: 1px;
              background: linear-gradient(90deg, #3a8cfc, #3a4efc);
            }
          }
          .rank_val{
            width: 30px;
            text-align: center;
          }
        }
        .rank_item:nth-child(-n+3){
          .rank_content{
            .rank_progress{
              background: linear-gradient(90deg, #FB393C, #FB396D);
            }
          }
        }
        
      }
      .title_item{
        color: #ffffff;
        font-size: 16px;
        line-height: 24px;
      }
    }
    .total_item:nth-last-child(1){
      margin-right: 0;
    }
  }
  .h360{min-height: 360px; height: 360px;}
  .h484{
    min-height: 484px;
    height: 484px;
    flex: 1;
  }
  .h420{
    height: 420px !important;
  }
  .marBottom20{margin-bottom: 20px;}
}
</style>